# -*- coding: utf-8

import wx
import logging
import traceback

import wx.lib.mixins.listctrl as listmix
# from gui_base import MainFrameBase
from gui_wx import MainFrameBase
import readzip
import builder

from mylog import logger

class XmindFileDropTarget(wx.FileDropTarget):
  def __init__(self, parent):
     wx.FileDropTarget.__init__(self)
     self.parent = parent

  def OnDropFiles(self, x, y, filenames):
    for file in filenames:
      logger.debug( "[FileDrop] " +  file )
      if file.endswith( '.xmind' ):
         self.parent.OpenFile( file )
         return True
    
    return False

class MainFrame( MainFrameBase, listmix.ColumnSorterMixin ):

  def __init__(self, parent):
    super(MainFrame, self).__init__(parent)
    
    # create list columns
    listctl = self.m_todoListCtrl
    listctl.InsertColumn( 0, 'priority', format = wx.LIST_FORMAT_RIGHT, width = 40 )
    listctl.InsertColumn( 1, 'progress', format = wx.LIST_FORMAT_RIGHT, width = 60 )
    listctl.InsertColumn( 2, 'note', width = 40 )
    listctl.InsertColumn( 3, 'title' )
    logger.debug( "Init complete" )
    
    listmix.ColumnSorterMixin.__init__(self, listctl.GetColumnCount() )
    
    # enable file drop acceptance
    self.droptarget = XmindFileDropTarget(self)
    listctl.SetDropTarget( self.droptarget )
    self.OnListSizeChanged( None )

  # For sort mixin
  def GetListCtrl(self):
    return self.m_todoListCtrl

  def GetSecondarySortValues(self, col, key1, key2):
    """ col: index of the column for which the sort is performed.
        key1, key2: the keys of two compared items
    """
    logger.debug( "[GetSecondarySortValues] col=%d, key = ( %d, %d )" % (col, key1, key2))
    second_col = None
    if col == 0:
      second_col = 1
    else:
      second_col = 0

    if second_col is not None:
      return ( self.itemDataMap[key1][second_col], self.itemDataMap[key2][second_col] )
    
    return ( key1, key2 )

  def OpenFile(self, filename):
    try:
      r = builder.parse_xmind( filename )
      self.update_list( r )
      self.setCaption( filename )
    except IOError, e:
      logger.warning( u"IOError in parse_xmind :" + filename )
      trace = traceback.format_exc()
      
      wx.MessageDialog( self, u"File open error : " + filename + u"\r\n" + trace, \
        style = wx.OK | wx.ICON_EXCLAMATION ).ShowModal()
    
  def update_list(self, todo_items):
    "Update list view with given data"
    self.clear_contents()
    
    list = self.m_todoListCtrl
    
    self.itemDataMap = todo_items
    idx = 0
    for item in todo_items:
      li = wx.ListItem()
      li.SetId( idx )
      li.SetData( idx )
      li.SetColumn( 0 )
      li.SetMask( wx.LIST_MASK_TEXT | wx.LIST_MASK_DATA )
      li.SetText( item.getPriorityStr() )
      list.InsertItem( li )

      list.SetStringItem(idx, 1, item.getProgressStr() )
      list.SetStringItem(idx, 2, (item.note is None) and "N" or "Y" )
      list.SetStringItem(idx, 3, item.title )
      idx = idx + 1

    # sort by priority
    self.SortListItems(0, 1)
    

  def OnListSizeChanged( self, event ):
    """Change of window size of the list control.
       Adjust column width of title"""
    columns = self.m_todoListCtrl.GetColumnCount()
    (window_width, window_height) = self.m_todoListCtrl.GetClientSizeTuple()
    
    cwidth = 0
    for i in xrange(columns):
      cwidth += self.m_todoListCtrl.GetColumnWidth( i )
    twidth = self.m_todoListCtrl.GetColumnWidth( 3 )
    twidth = window_width - (cwidth - twidth)
    self.m_todoListCtrl.SetColumnWidth( 3, twidth )

  def clear_contents(self):
    self.m_todoListCtrl.DeleteAllItems()

  def setCaption(self, name):
    if name is None:
      self.SetTitle( u'ToDo' )
    else:
      self.SetTitle( u'ToDo - ' + name )

  def doFileOpen( self, event ):
    # open dialog to choose a file
    dlg = wx.FileDialog( self,
      message = 'Open xmind book',
      wildcard = '*.xmind',
      style = wx.FD_FILE_MUST_EXIST )
    
    if dlg.ShowModal() == wx.ID_OK:
      filename = dlg.GetFilename()
      # read file
      self.OpenFile(filename)

  def doQuit( self, event ):
    # show a dialog to confirm closing window
    self.Close()
    
  def OnClose( self, event ):
    dlg = wx.MessageDialog( self, "Are you sure you want to close this window?", style = wx.YES_NO  | wx.YES_DEFAULT )
    if dlg.ShowModal() == wx.ID_YES:
      self.Destroy()


if __name__ == '__main__':
  logging.basicConfig(level=logging.DEBUG)
  file = None

  import sys
  if len(sys.argv) >= 2:
    file = sys.argv[1].decode( sys.getfilesystemencoding() or 'ascii' )

  app = wx.PySimpleApp()

  my = MainFrame(None)
  if file:
    my.OpenFile( file )
  my.Show()
  app.MainLoop()
